﻿//Copyright (c) 2010 William Liu, Enoch Ye
//William Liu <william.lyz@gmail.com>
//Enoch Ye <moonlight.enoch@gmail.com>

//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at

//       http://www.apache.org/licenses/LICENSE-2.0

//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//Own libs
using GBG_DBM.Support.DAL;
using GBG_DBM.GlobalParameters;
using GBG_DBM.UI;
using GBG_DBM.Support.DAL.Entities;
using GBG_DBM.Reporting.ReportForms;
using GBG_DBM.Support.DAL.DB;
using GBG_DBM.Database;

namespace GBG_DBM.UI
{
    public partial class Main_UI : Form
    {

        #region FILEDS
        
        private CUR _CUR = new CUR();
        private static readonly Main_UI main = new Main_UI();
        public static  Main_UI getInstance() 
        {
            return main;
        }
         
        #endregion

        #region PROPERTIES
        private DBAccessory _DBAccessory;
        private int CurrentRowIndex;
		private DataTable _CurrentSupplier_RMs;
		public DataTable CurrentSupplier_RMs
		{
			get
			{
				if (_CurrentSupplier_RMs == null) 
				{
					setCurrentSupplierRMs();
				}
				return _CurrentSupplier_RMs; }
			set { _CurrentSupplier_RMs = value; }
		}
		private Supplier_RM _CurrentSupplier_RM;
		public Supplier_RM CurrentSupplier_RM
		{
			get { return _CurrentSupplier_RM; }
			set { _CurrentSupplier_RM = value; }
		}
        private DataTable _CurrentIngredients;
        public DataTable CurrentIngredients
        {
            get
            {
                if (_CurrentIngredients == null) 
                {
                    setCurrentIngredients();
                } 
                return _CurrentIngredients; }
            set { _CurrentIngredients = value; }
        }
        private Ingredient _CurrentIngredient;
        public Ingredient CurrentIngredient
        {
            get { return _CurrentIngredient; }
            set { _CurrentIngredient = value; }
        }
        private DataTable _CurrentFreights;
        public DataTable CurrentFreights
        {
            get
            {
                if (_CurrentFreights == null)
                {
                    setCurrentFreights();
                } return _CurrentFreights;
            }
            set { _CurrentFreights = value; }
        }
        private Freight _CurrentFreight;
        public Freight CurrentFreight
        {
            get { return _CurrentFreight; }
            set { _CurrentFreight = value; }
        }
        private DataTable _CurrentRawMaterialSuppliers;
        public DataTable CurrentRawMaterialSuppliers
        {
            get
            {
                if (_CurrentRawMaterialSuppliers == null) 
                {
                    setCurrentRawMaterialSuppliers();
                }
                return _CurrentRawMaterialSuppliers; }
            set { _CurrentRawMaterialSuppliers = value; }
        }
        private RawMaterialSupplier _CurrentRawMaterialSupplier;
        public RawMaterialSupplier CurrentRawMaterialSupplier
        {
            get { return _CurrentRawMaterialSupplier; }
            set { _CurrentRawMaterialSupplier = value; }
        }
        private DataTable _CurrentCurrencies;
        public DataTable CurrentCurrencies
        {
            get
            {
                if (_CurrentCurrencies == null) 
                {
                    setCurrentCurrencies();
                }  
                return _CurrentCurrencies;
            }
            set { _CurrentCurrencies = value; }
        }
        private CUR _CurrentCurrency;
        public CUR CurrentCurrency
        {
            get { return _CurrentCurrency; }
            set { _CurrentCurrency = value; }
        }
        private DataTable _CurrentSTDs;
        public DataTable CurrentSTDs
        {
            get
            {
                if (_CurrentSTDs == null) 
                {
					setCurrentSTDs();
                } 
                return _CurrentSTDs; }
            set { _CurrentSTDs = value; }
        }
        private STD _CurrentSTD;
        public STD CurrentSTD
        {
            get { return _CurrentSTD; }
            set { _CurrentSTD = value; }
        }
        private DataTable _CurrentPackages;
        public DataTable CurrentPackages
        {
            get
            {
                if (_CurrentPackages == null) 
                {
                    setCurrentPackages();
                } 
                return _CurrentPackages; }
            set { _CurrentPackages = value; }
        }
        private Packaging _CurrentPackage;
        public Packaging CurrentPackage
        {
            get { return _CurrentPackage; }
            set { _CurrentPackage = value; }
        }
        #endregion

        #region CONSTRUCTORS

        public Main_UI()
        {
            InitializeComponent();

            this.Add_CurrencyInfo_Currency_Tab.Enabled = false;

            //keyboard events
            txtNewCurrency.KeyUp += new KeyEventHandler(txtNewCurrency_KeyUp);
            txtNewCurrencyToNZD.KeyUp += new KeyEventHandler(txtNewCurrencyToNZD_KeyUp);
            txtNewCurrencyToNZD.KeyPress +=new KeyPressEventHandler(txtNewCurrencyToNZD_KeyPress);

        }

        #endregion

        #region KeyBorad events

        private void txtNewCurrency_KeyUp(object sender, KeyEventArgs e)
        {
            if (txtNewCurrency.Text != string.Empty && txtNewCurrencyToNZD.Text != string.Empty)
            {
                this.Add_CurrencyInfo_Currency_Tab.Enabled = true;
            }
            else
            {
                this.Add_CurrencyInfo_Currency_Tab.Enabled = false;
            }
        }

        private void txtNewCurrencyToNZD_KeyUp(object sender, KeyEventArgs e)
        {
            if (txtNewCurrency.Text != string.Empty && txtNewCurrencyToNZD.Text != string.Empty)
            {
                this.Add_CurrencyInfo_Currency_Tab.Enabled = true;
            }
            else
            {
                this.Add_CurrencyInfo_Currency_Tab.Enabled = false;
            }
        }

        /// <summary>
        /// Only alow input numbers and decimal point
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtNewCurrencyToNZD_KeyPress(object sender, KeyPressEventArgs e)
        {
            string _nzd = txtNewCurrencyToNZD.Text;
            //alow enter number
            e.Handled = e.KeyChar < '0' || e.KeyChar > '9';
            //alow backspace key. askii = 8
            if (e.KeyChar == (char)8)
            {
                e.Handled = false;
            }
            //decimal point, askii = 46
            if (e.KeyChar == (char)46)
            {
                //the first enter can not be a decimal point
                if (_nzd == string.Empty)
                {
                    e.Handled = true;
                    return;
                }
                //only allow enter one decimal point
                else
                {
                    foreach (char _ch in _nzd)
                    {
                        if (char.IsPunctuation(_ch))
                        {
                            e.Handled = true;
                            return;
                        }
                    }
                    e.Handled = false;
                }
            }
        }

        #endregion

        #region METHODS

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
            
        private void resetDatabasePasswordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Program.form = new Setting_UI();
            Setting_UI SettingWindow = new Setting_UI();
            SettingWindow.Owner = this;

            SettingWindow.Shown += new EventHandler(SettingWindow_Shown);
            SettingWindow.FormClosed += new FormClosedEventHandler(SettingWindow_Closed);

            SettingWindow.Show();
            //this.Enabled = false;
        }

        //disable main ui when user open setting window
        //here can use ShowDialog() to repleace this function
        private void SettingWindow_Shown(object sender, EventArgs e)
        {
            this.Enabled = false;
            ((Form)sender).Focus();
        }

        //re-enable main ui when user close setting window
        private void SettingWindow_Closed(object sender, EventArgs e)
        {
            this.Enabled = true;
        }

        //open About window
        private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            About_UI AboutWindow = new About_UI();
            AboutWindow.ShowDialog();
        }

        /// <summary>
        /// for testing, will change the code to open menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void manualToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    //testing
        //    Test.TestPanel testpanel = new Test.TestPanel();
        //    testpanel.Show();
        //}

        #region Report Viewsers
        /// <summary>
        /// show currency report form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReportViewer_CurrencyTab_Click(object sender, EventArgs e)
        {
            CurrencyReport _currencyReport = new CurrencyReport();
            _currencyReport.ShowDialog();
        }

        /// <summary>
        /// show freight report form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Report_FreightTab_Click(object sender, EventArgs e)
        {
            FreightReport _freightReport = new FreightReport();
            _freightReport.ShowDialog();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            RawMetSupplierReport _RMSReport = new RawMetSupplierReport();
            _RMSReport.ShowDialog();
        }

        #endregion

		#region Add
		private void Add_CurrencyInfo_Currency_Tab_Click(object sender, EventArgs e)
		{
            string _currencyCode;
            decimal _nzd;

            _currencyCode = txtNewCurrency.Text;
            _nzd = Convert.ToDecimal(txtNewCurrencyToNZD.Text);

            this.Validate();
            this.cUREXCHBindingSource.EndEdit();
            this.cUR_EXCHTableAdapter.Insert(_currencyCode, _nzd);
            this.cUR_EXCHTableAdapter.Fill(this.gBDataSet.CUR_EXCH);

            //if (_CurrentCurrency == null)
            //{
            //    _DBAccessory = new DBAccessory();
            //    CUR Cur = new CUR();
            //    Cur.CurrencyName = txtNewCurrency.Text;
            //    Cur.NewZealandDollar = Convert.ToSingle(txtNewCurrencyToNZD.Text);
            //    _DBAccessory.addCUR(Cur);
            //    dgvCurrencyDataBind();
            //    txtNewCurrency.Clear();
            //    txtNewCurrencyToNZD.Clear();
            //}
            //else
            //{
            //    MessageBox.Show("Please Modify Current Currency prior to Add new one", "Warning");
            //}
		}

		private void btnAddSupplier_Click(object sender, EventArgs e)
        {
            DataTable Raw = GetRawSupplierList();
            DataTable Cur = GetCurrencyList();
            DataTable Freight = GetFreightList();
            DataTable Ingredient = GetIngredientList();
            if (Raw != null & Cur != null & Freight != null)
            {
                Supplier_RM_UI _Supplier = new Supplier_RM_UI(Raw, Cur, Freight, Ingredient);
                _Supplier.Show();
            }
            else 
            {
                MessageBox.Show("The Raw Material Supplier OR Freight OR Currency are inappropriate");
            }
        }

        private void btnFormula_Click(object sender, EventArgs e)
        {
            DataTable Raw = GetRawSupplierList();
            if (Raw != null)
            {
                AddIngredient_UI Ingredient = new AddIngredient_UI(Raw);
                Ingredient.Show();
            }
            else 
            {
                MessageBox.Show("Raw Material Supplier is not existing");
            }
        }
        private void btnAddFreight_Click(object sender, EventArgs e)
        {
            
            Freight_UI _Freight = new Freight_UI();
            _Freight.Show();
        }

        private void btnAddRawMaterial_Click(object sender, EventArgs e)
        {
            RawMaterialSupplier_UI _RawMaterialSupplier = new RawMaterialSupplier_UI();
            _RawMaterialSupplier.Show();
        }

        private void btnAddPackage_Click(object sender, EventArgs e)
        {
            Package_UI _Package = new Package_UI();
            _Package.Show();
        }
		private void Add_STDTab_Click(object sender, EventArgs e)
		{
			DataTable Supplier_RMList = GetSupplierRMList();
			DataTable PackageList = GetPackageList();
            if (Supplier_RMList != null & PackageList != null)
            {
                STD_UI STD = new STD_UI(Supplier_RMList, PackageList);
                STD.Show();
            }
            else 
            {
                MessageBox.Show("The Supplier RM OR Package are inappropriate");
            }
		}
		#endregion

		/// <summary>
        /// run calculator from system
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void caculatorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("calc.exe");
            }
            catch (Exception _Ex)
            {
                throw new Exception(_Ex.Message);
            }
        }
		

		/// <summary>
        /// run notepad from system
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notebookToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("notepad.exe");
            }
            catch (Exception _Ex)
            {
                throw new Exception(_Ex.Message);
            }
        }

        /// <summary>
        /// run microsoft word from system
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void wordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("WINWORD.EXE");
            }
            catch (Exception _Ex)
            {
                throw new Exception(_Ex.Message);
            }
        }

        /// <summary>
        /// run microsoft office excel from system
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
          private void excelToolStripMenuItem_Click(object sender, EventArgs e)
        {
              try
            {
                System.Diagnostics.Process.Start("EXCEL.EXE");
            }
            catch (Exception _Ex)
            {
                throw new Exception(_Ex.Message);
            }
        }


        #endregion

        #region Window load section

        /// <summary>
        /// fill data to datagridview
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
          private void Main_UI_Load(object sender, EventArgs e)
          {
              // TODO: 这行代码将数据加载到表“gBDataSet.Product_List”中。您可以根据需要移动或删除它。
              this.product_List.Fill(this.gBDataSet.Product_List);
              // TODO: 这行代码将数据加载到表“gBDataSet.CUR_EXCH”中。您可以根据需要移动或删除它。
              this.cUR_EXCHTableAdapter.Fill(this.gBDataSet.CUR_EXCH);
              // TODO: 这行代码将数据加载到表“gBDataSet.Product_List”中。您可以根据需要移动或删除它。
              this.product_List.Fill(this.gBDataSet.Product_List);
              // TODO: 这行代码将数据加载到表“gBDataSet.CUR_EXCH”中。您可以根据需要移动或删除它。
              this.cUR_EXCHTableAdapter.Fill(this.gBDataSet.CUR_EXCH);

              setFromControlAndLoadData();
          }

        #endregion

          private void tabMain_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        #region DataTable
		private void setCurrentSupplierRMs()
		{
			_CurrentSupplier_RMs = new DataTable("Supplier RM");
			_CurrentSupplier_RMs.Columns.Add("Code");
            _CurrentSupplier_RMs.Columns.Add("Category");
			_CurrentSupplier_RMs.Columns.Add("Trade_Name");
			_CurrentSupplier_RMs.Columns.Add("INCI_Name");
			_CurrentSupplier_RMs.Columns.Add("Key_Property");
			_CurrentSupplier_RMs.Columns.Add("Supplier_Code");
			_CurrentSupplier_RMs.Columns.Add("Supplier_Name");
			_CurrentSupplier_RMs.Columns.Add("Supplier_Country");
			_CurrentSupplier_RMs.Columns.Add("Currency");
			_CurrentSupplier_RMs.Columns.Add("Local_Price");
			_CurrentSupplier_RMs.Columns.Add("Estimated_Cost");
			_CurrentSupplier_RMs.Columns.Add("Freight_Type");
            _CurrentSupplier_RMs.Columns.Add("Estimated_Loss");
			_CurrentSupplier_RMs.Columns.Add("Estimated_Freight");
            _CurrentSupplier_RMs.Columns.Add("Total_Cost");
            _CurrentSupplier_RMs.Columns.Add("Pack_Size");
            _CurrentSupplier_RMs.Columns.Add("Estimated_DateForm");
			_CurrentSupplier_RMs.Columns.Add("Estimated_DateTo");
			_CurrentSupplier_RMs.Columns.Add("Total_Cost_of_Shipment");
		}
        private void setCurrentIngredients() 
        {
            _CurrentIngredients = new DataTable("Ingredient");
            _CurrentIngredients.Columns.Add("Code");
            _CurrentIngredients.Columns.Add("Supplier_Code");
            _CurrentIngredients.Columns.Add("Supplier_Name");
            _CurrentIngredients.Columns.Add("INCINAME");
            _CurrentIngredients.Columns.Add("TradeName");
            _CurrentIngredients.Columns.Add("KeyProperty");
            _CurrentIngredients.Columns.Add("LocalPrice");
            _CurrentIngredients.Columns.Add("Category");
        }
		private void setCurrentSTDs() 
		{
            _CurrentSTDs = new DataTable("STD");
            _CurrentSTDs.Columns.Add("Product Code");
            _CurrentSTDs.Columns.Add("Product Name");
            _CurrentSTDs.Columns.Add("Product Ingredient");
            _CurrentSTDs.Columns.Add("Product Unit");
            _CurrentSTDs.Columns.Add("Description");
            _CurrentSTDs.Columns.Add("Comments");
            _CurrentSTDs.Columns.Add("Datatime");
            _CurrentSTDs.Columns.Add("Loss");
            _CurrentSTDs.Columns.Add("Batch size");
            _CurrentSTDs.Columns.Add("RRP");
            _CurrentSTDs.Columns.Add("Package");
            _CurrentSTDs.Columns.Add("Total ");
            _CurrentSTDs.Columns.Add("Objective");
            _CurrentSTDs.Columns.Add("RawMat");
            _CurrentSTDs.Columns.Add("Biogro");
		}
        private void setCurrentCurrencies()
        {
            _CurrentCurrencies = new DataTable("Currency");
            _CurrentCurrencies.Columns.Add("Currency");
            _CurrentCurrencies.Columns.Add("NZD");
        }
        private void setCurrentRawMaterialSuppliers() 
        {
            _CurrentRawMaterialSuppliers = new DataTable("Raw_Material_Supplier");
            _CurrentRawMaterialSuppliers.Columns.Add("Supplier_Code");
            _CurrentRawMaterialSuppliers.Columns.Add("Supplier_Name");
            _CurrentRawMaterialSuppliers.Columns.Add("Address");
            _CurrentRawMaterialSuppliers.Columns.Add("Phone");
            _CurrentRawMaterialSuppliers.Columns.Add("Email");
            _CurrentRawMaterialSuppliers.Columns.Add("Contact");
            _CurrentRawMaterialSuppliers.Columns.Add("Category");
            _CurrentRawMaterialSuppliers.Columns.Add("Notes");
        }
        private void setCurrentFreights() 
        {
            _CurrentFreights = new DataTable("Freight");
            _CurrentFreights.Columns.Add("Freight_Type");
            _CurrentFreights.Columns.Add("Estimated_Cost");
            _CurrentFreights.Columns.Add("Supplier");
            _CurrentFreights.Columns.Add("Origin");
            _CurrentFreights.Columns.Add("Rate_Type");
            _CurrentFreights.Columns.Add("Product_Weight");
            _CurrentFreights.Columns.Add("Package_Weight");
            _CurrentFreights.Columns.Add("Total_Weight");
            _CurrentFreights.Columns.Add("Supplier_Price");
            _CurrentFreights.Columns.Add("Variable_Fuel_Component");
        }
 
        private void setCurrentPackages() 
        {
            _CurrentPackages = new DataTable("Package");
            _CurrentPackages.Columns.Add("Package");
            _CurrentPackages.Columns.Add("Price");
        }
        private void SetDataGridFormat() 
        {
			//dgvSupplierRM
			this.dgvSupplierRM.Columns["Code"].HeaderText="Code";
            this.dgvSupplierRM.Columns["Category"].HeaderText = "Category";
			this.dgvSupplierRM.Columns["Trade_Name"].HeaderText="Trade Name";
			this.dgvSupplierRM.Columns["INCI_Name"].HeaderText="INCI Name";
			this.dgvSupplierRM.Columns["Key_Property"].HeaderText="Key Property";
			this.dgvSupplierRM.Columns["Supplier_Code"].HeaderText="Supplier Code";
			this.dgvSupplierRM.Columns["Supplier_Name"].HeaderText="Supplier Name";
			this.dgvSupplierRM.Columns["Supplier_Country"].HeaderText="Supplier Country";
			this.dgvSupplierRM.Columns["Currency"].HeaderText="Currency";
			this.dgvSupplierRM.Columns["Local_Price"].HeaderText="Local Price";
			this.dgvSupplierRM.Columns["Estimated_Cost"].HeaderText="Estimated Cost";
			this.dgvSupplierRM.Columns["Freight_Type"].HeaderText="Freight Type";
			this.dgvSupplierRM.Columns["Estimated_Freight"].HeaderText="Estimated Freight Cost";
			this.dgvSupplierRM.Columns["Estimated_Loss"].HeaderText="Estimated Loss";
			this.dgvSupplierRM.Columns["Pack_Size"].HeaderText="Pack Size";
			this.dgvSupplierRM.Columns["Estimated_DateForm"].HeaderText="Estimated Date From";
			this.dgvSupplierRM.Columns["Estimated_DateTo"].HeaderText="Estimated Date To";
			this.dgvSupplierRM.Columns["Total_Cost"].HeaderText="Total Cost";
			this.dgvSupplierRM.Columns["Total_Cost_of_Shipment"].HeaderText = "Total Cost Of Shipment";
            //dgvCurrency
            //this.dgvCurrency.Columns["Currency"].FillWeight = 100;
            //this.dgvCurrency.Columns["NZD"].FillWeight = 50;
            //this.dgvCurrency.Columns["Currency"].HeaderText = "Currency";
            //this.dgvCurrency.Columns["NZD"].HeaderText = "NZD";
            //dgvPackage
            this.dgvPackage.Columns["Package"].FillWeight = 100;
            this.dgvPackage.Columns["Price"].FillWeight = 100;
            this.dgvPackage.Columns["Package"].HeaderText = "Package";
            this.dgvPackage.Columns["Price"].HeaderText = "Price";
            //dgvIngrident
            this.dgvIngredient.Columns["Code"].HeaderText = "Ingredient Code";
            this.dgvIngredient.Columns["Supplier_Name"].HeaderText = "Supplier Name";
;           this.dgvIngredient.Columns["Supplier_Code"].HeaderText = "Supplier Code";
            this.dgvIngredient.Columns["INCIName"].HeaderText = "INCI Name";
            this.dgvIngredient.Columns["TradeName"].HeaderText = "Trade Name";
            this.dgvIngredient.Columns["KeyProperty"].HeaderText = "Key Property";
            this.dgvIngredient.Columns["LocalPrice"].HeaderText = "Local Price";
            this.dgvIngredient.Columns["Category"].HeaderText = "Category";
            //dgvRawMaterialSupplier
            this.dgvRawMaterialSupplier.Columns["Supplier_Code"].HeaderText = "Supplier Code";
            this.dgvRawMaterialSupplier.Columns["Supplier_Name"].HeaderText = "Supplier Name";
            this.dgvRawMaterialSupplier.Columns["Address"].HeaderText = "Address";
            this.dgvRawMaterialSupplier.Columns["Phone"].HeaderText = "Phone";
            this.dgvRawMaterialSupplier.Columns["Email"].HeaderText = "Email";
            this.dgvRawMaterialSupplier.Columns["Contact"].HeaderText = "Contact";
            this.dgvRawMaterialSupplier.Columns["Category"].HeaderText = "Category";
            this.dgvRawMaterialSupplier.Columns["Notes"].HeaderText = "Notes";
            //dgvFreight
            this.dgvFreight.Columns["Freight_Type"].HeaderText = "Freight Type";
            this.dgvFreight.Columns["Estimated_Cost"].HeaderText = "Estiamte Cost";
            this.dgvFreight.Columns["Supplier"].HeaderText = "Supplier";
            this.dgvFreight.Columns["Origin"].HeaderText = "Origin";
            this.dgvFreight.Columns["Rate_Type"].HeaderText = "Rate Type";
            this.dgvFreight.Columns["Product_Weight"].HeaderText = "Product Weight";
            this.dgvFreight.Columns["Package_Weight"].HeaderText = "Package Weight";
            this.dgvFreight.Columns["Total_Weight"].HeaderText = "Total Weight";
            this.dgvFreight.Columns["Supplier_Price"].HeaderText = "Supplier Price";
            this.dgvFreight.Columns["Variable_FuelComponent"].HeaderText = "Variable Fuel Component";

        }
		private void AddRowToSTDGrid(DataTable STD, DataRowView drv) 
		{
			if (STD != null) 
			{
                STD.Rows.Add(drv["Product_ID"], drv["Product_Name"], drv["Product_Ingredient"], drv["Product_Unit"], drv["Description"],
                    drv["Comments"], drv["DateTime"], drv["Loss"], drv["Batch_Size"], drv["RRP"], drv["Package"], drv["Total"], drv["Objective"],
                    drv["RawMat"], drv["Biogro"]);
			}
		}
		private void AddRowToSupplierRMGrid(DataTable SupplierRM, DataRowView drv) 
		{
           
			if (SupplierRM != null) 
			{
                SupplierRM.Rows.Add(drv["Code"], drv["Category"], drv["Trade_Name"], drv["INCI_Name"], drv["Key_Properties"], drv["Supplier_Code"]
                    , drv["Supplier_Name"], drv["Supplier_Country"], drv["Currency_Name"], drv["Local_Price"], drv["Estimate_Cost"],
                    drv["Freight_Type"], drv["Estimate_Loss"], drv["Estimate_Price"], drv["Total_Cost"], drv["Pack_Size"], drv["Estimate_DateFrom"],
                    drv["Estimate_DateTo"], drv["Total_Cost_of_Shipment"]);
			}
		}
        private void AddRowToCurrencyGrid(DataTable Currencies, DataRowView drv) 
        {
            if (Currencies != null)
            {
                Currencies.Rows.Add(drv["Currency_Code"], drv["NZD"]);
            }
        }
        private void AddRowToPackageGrid(DataTable Packages, DataRowView drv) 
        {
            if (Packages != null) 
            {
                Packages.Rows.Add(drv["Package"], drv["Cost"]);
            }
        }
        private void AddRowToIngredientGrid(DataTable Ingredients, DataRowView drv) 
        {
            if (Ingredients != null) 
            {
                Ingredients.Rows.Add(drv["Code"], drv["Supplier Code"],drv["Supplier_Name"], drv["INCINAME"], drv["TradeName"], drv["KeyProperty"],
                    drv["LocalPrice"], drv["Category"]);
            }
        }
        private void AddRowToRawMaterialSupplierGrid(DataTable RawMaterialSuppliers, DataRowView drv) 
        {
            if (RawMaterialSuppliers != null) 
            {
                RawMaterialSuppliers.Rows.Add(drv["Supplier_Code"],drv["Supplier_Name"],drv["Address"],drv["Phone"]
                    ,drv["Email"],drv["Contact"],drv["Category"],drv["Notes"]);
            }
        }
        private void AddRowToFreightGrid(DataTable Freights, DataRowView drv) 
        {
            if (Freights != null) 
            {
                Freights.Rows.Add(drv["Freight_Type"], drv["Estimated_Cost"], drv["Supplier"], drv["Origin"], drv["Rate_Type"]
                    , drv["Product_Weight"], drv["Packaging_Weight"], drv["Total_Weight"], drv["Supplier_Price"], drv["Variable_FuelComponent"]);
            }
        }
        #endregion

        private void Refresh_Click(object sender, EventArgs e)
        {
            setFromControlAndLoadData();
        }

		#region GetList
		private DataTable GetSTDList()
		{
			STDDB _STD=new STDDB();
            DataTable dt = _STD.getSTDs();
			CurrentSTDs=null;
			foreach(DataRowView drv in dt.DefaultView)
			{
				AddRowToSTDGrid(CurrentSTDs,drv);
			}
			return _CurrentSTDs;
		}
		private DataTable GetSupplierRMList()
		{
			SupplierRMDB _SupplierRMDB=new SupplierRMDB();
			DataTable dt=_SupplierRMDB.getSupplierRMS();
			CurrentSupplier_RMs=null;
			foreach(DataRowView drv in dt.DefaultView)
			{
				AddRowToSupplierRMGrid(CurrentSupplier_RMs, drv);
			}
			return _CurrentSupplier_RMs;
		}

		private DataTable GetIngredientList() 
        {
            IngredientDB _Ingredient = new IngredientDB();
            DataTable dt = _Ingredient.getIngredients();
            CurrentIngredients = null;
            foreach (DataRowView drv in dt.DefaultView) 
            {
                AddRowToIngredientGrid(CurrentIngredients, drv);
            }
            return _CurrentIngredients;
        }
        private DataTable GetPackageList() 
        {
            PackageDB _Package = new PackageDB();
            DataTable dt = _Package.getPackages();
            CurrentPackages = null;
            foreach (DataRowView drv in dt.DefaultView)
            {
                AddRowToPackageGrid(CurrentPackages, drv);
            }
            return _CurrentPackages;
        }
        private DataTable GetCurrencyList() 
        {
            CurrencyDB _Currency=new CurrencyDB();
            DataTable dt = _Currency.getCurrencies();
            CurrentCurrencies = null;
            foreach(DataRowView drv in dt.DefaultView)
            {
                AddRowToCurrencyGrid(CurrentCurrencies, drv);
            }
            return _CurrentCurrencies;
        }
        private DataTable GetRawSupplierList() 
        {
            RawMaterialSupplierDB _RawMaterialSupplier = new RawMaterialSupplierDB();
            DataTable dt = _RawMaterialSupplier.GetRawMaterialSuppliers();
            CurrentRawMaterialSuppliers = null;
            foreach (DataRowView drv in dt.DefaultView) 
            {
                AddRowToRawMaterialSupplierGrid(CurrentRawMaterialSuppliers, drv);
            }
            return _CurrentRawMaterialSuppliers;
        }
        private DataTable GetFreightList() 
        {
            FreightDB _Freight = new FreightDB();
            DataTable dt = _Freight.getFreights();
            CurrentFreights = null;
            foreach (DataRowView drv in dt.DefaultView) 
            {
                AddRowToFreightGrid(CurrentFreights, drv);
            } 
            return _CurrentFreights;
        }
#endregion

        #region DataGridView Event
		private void dgvSTD_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			STD_UI STD = new STD_UI(_CurrentSTD);
			STD.Show();
		}
		private void dgvIngredient_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			AddIngredient_UI Ingredient = new AddIngredient_UI(_CurrentIngredient);
			Ingredient.Show();
		}

		private void dgvSupplierRM_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			Supplier_RM_UI Supplier_RM_UI = new Supplier_RM_UI(_CurrentSupplier_RM);
			Supplier_RM_UI.Show();
		}
        //private void dgvCurrency_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        //{
        //    txtNewCurrency.Text = _CurrentCurrency.CurrencyName;
        //    txtNewCurrency.Enabled = false;
        //    txtNewCurrencyToNZD.Text = Convert.ToString(_CurrentCurrency.NewZealandDollar);
        //}
		private void dgvRawMaterialSupplier_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			RawMaterialSupplier_UI Raw = new RawMaterialSupplier_UI(_CurrentRawMaterialSupplier);
			Raw.Show();
		}
		private void dgvFreight_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			Freight_UI Freight = new Freight_UI(_CurrentFreight);
			Freight.Show();
		}
		private void dgvPackage_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			Package_UI Package = new Package_UI(_CurrentPackage);
			Package.Show();
		}
        public void activateButton() 
        {
            Add_PackageTab.Enabled = true;
            Edit_PackageTab.Enabled = true;
        }
		private void dgvSupplierRM_RowEnter(object sender, DataGridViewCellEventArgs e)
		{
			string SupplierRMCode;
			_CurrentSupplier_RM = new Supplier_RM();
			if (e.RowIndex > -1)
			{
				CurrentRowIndex = e.RowIndex;
				this.dgvSupplierRM.Rows[CurrentRowIndex].Selected = true;
				SupplierRMCode = (string)this.dgvSupplierRM[0, CurrentRowIndex].Value;
				_DBAccessory = new DBAccessory();
				_CurrentSupplier_RM = _DBAccessory.getSupplierByCode(SupplierRMCode);
			}
		}
		private void dgvSTD_RowEnter(object sender, DataGridViewCellEventArgs e)
		{
			string STDCode;
			_CurrentSTD = new STD();
			if (e.RowIndex > -1)
			{
				CurrentRowIndex = e.RowIndex;
				this.dgvSTD.Rows[CurrentRowIndex].Selected = true;
				STDCode = (string)this.dgvSTD[0, CurrentRowIndex].Value;
				_DBAccessory = new DBAccessory();
				_CurrentSTD = _DBAccessory.getSTDByCode(STDCode);
			}
		}
        //private void dgvCurrency_RowEnter(object sender, DataGridViewCellEventArgs e)
        //{
        //    string CurrentCurrency;
        //    _CurrentCurrency = new CUR();
        //    if (e.RowIndex > -1)
        //    {
        //        CurrentRowIndex = e.RowIndex;
        //        this.dgvCurrency.Rows[CurrentRowIndex].Selected = true;
        //        CurrentCurrency = (string)this.dgvCurrency[0, CurrentRowIndex].Value;
        //        _DBAccessory = new DBAccessory();
        //        _CurrentCurrency = _DBAccessory.getCURbyCurrency(CurrentCurrency);
        //    }
        //}

		private void dgvIngredient_RowEnter(object sender, DataGridViewCellEventArgs e)
		{
			string IngredientCode;
			_CurrentIngredient = new Ingredient();
			if (e.RowIndex > -1)
			{
				CurrentRowIndex = e.RowIndex;
				this.dgvIngredient.Rows[CurrentRowIndex].Selected = true;
				IngredientCode = (string)this.dgvIngredient[0, CurrentRowIndex].Value;
				_DBAccessory = new DBAccessory();
				_CurrentIngredient = _DBAccessory.getIngredientByCode(IngredientCode);

			}
		}
		private void dgvRawMaterialSupplier_RowEnter(object sender, DataGridViewCellEventArgs e)
		{
			string RawSupplierCode;

			_CurrentRawMaterialSupplier = new RawMaterialSupplier();
			if (e.RowIndex > -1)
			{
				CurrentRowIndex = e.RowIndex;
				this.dgvRawMaterialSupplier.Rows[CurrentRowIndex].Selected = true;
				RawSupplierCode = (string)this.dgvRawMaterialSupplier[0, CurrentRowIndex].Value;
				_DBAccessory = new DBAccessory();
				_CurrentRawMaterialSupplier = _DBAccessory.getRawMaterialSupplierByCode(RawSupplierCode);

			}
		}
		private void dgvFreight_RowEnter(object sender, DataGridViewCellEventArgs e)
		{
			string FreightType;

			_CurrentFreight = new Freight();
			if (e.RowIndex > -1)
			{
				CurrentRowIndex = e.RowIndex;
				this.dgvFreight.Rows[CurrentRowIndex].Selected = true;
				FreightType = (string)this.dgvFreight[0, CurrentRowIndex].Value;
				_DBAccessory = new DBAccessory();
				_CurrentFreight = _DBAccessory.getFreightByType(FreightType);

			}
		}
		private void dgvPackage_RowEnter(object sender, DataGridViewCellEventArgs e)
		{
			string PackageId;

			_CurrentPackage = new Packaging();
			if (e.RowIndex > -1)
			{
				CurrentRowIndex = e.RowIndex;
				this.dgvPackage.Rows[CurrentRowIndex].Selected = true;
				PackageId = (string)this.dgvPackage[0, CurrentRowIndex].Value;
				_DBAccessory = new DBAccessory();
				_CurrentPackage = _DBAccessory.getPackageById(PackageId);

			}
		}
        
        #endregion

		#region Add

		#endregion

		#region Edit
		private void Edit_PackageTab_Click(object sender, EventArgs e)
		{
			if (_CurrentPackage == null)
			{
				MessageBox.Show("Please select one Package.");
			}
			else
			{
				Package_UI Package = new Package_UI(_CurrentPackage);

				Package.Show();
			}
		}

		private void Edit_RawMaterialTab_Click(object sender, EventArgs e)
		{
			if (_CurrentRawMaterialSupplier == null)
			{
				MessageBox.Show("Please select one.");
			}
			else
			{
				RawMaterialSupplier_UI Raw = new RawMaterialSupplier_UI(_CurrentRawMaterialSupplier);
				Raw.Show();
			}
		}



		private void Edit_FreightTab_Click(object sender, EventArgs e)
		{
			if (_CurrentFreight == null)
			{
				MessageBox.Show("Please select one.");
			}
			else
			{
				Freight_UI Freight = new Freight_UI(_CurrentFreight);
				Freight.Show();
			}
		}

		private void Edit_SupplierTab_Click(object sender, EventArgs e)
		{
			if (_CurrentSupplier_RM == null)
			{

			}
			else 
			{ 
			Supplier_RM_UI Supplier_RM = new Supplier_RM_UI(_CurrentSupplier_RM);
			Supplier_RM.Show();
			}
		}

		private void Edit_FormulaTab_Click(object sender, EventArgs e)
		{
			if (_CurrentIngredient == null)
			{
				MessageBox.Show("Please select one.");
			}
			else
			{
				AddIngredient_UI Ingredient = new AddIngredient_UI(_CurrentIngredient);
				Ingredient.Show();
			}
		}
		private void Update_CurrencyTab_Click(object sender, EventArgs e)
		{
            this.Validate();
            this.cUREXCHBindingSource.EndEdit();
            this.cUR_EXCHTableAdapter.Update(this.gBDataSet.CUR_EXCH);
            this.cUR_EXCHTableAdapter.Fill(this.gBDataSet.CUR_EXCH);
            //if (txtNewCurrency.Text.Length == 0 || txtNewCurrencyToNZD.Text.Length == 0)
            //{
            //    MessageBox.Show("Please Select one", "Warning");
            //}
            //else if (_CurrentCurrency == null) { }
            //else
            //{

            //    _CurrentCurrency.NewZealandDollar = Convert.ToSingle(txtNewCurrencyToNZD.Text);
            //    _DBAccessory = new DBAccessory();
            //    _DBAccessory.setCUR(_CurrentCurrency);
            //    dgvCurrencyDataBind();
			//}
		}
		private void Edit_STDTab_Click(object sender, EventArgs e)
		{
			if (_CurrentSTD == null)
			{
				MessageBox.Show("Please select one.");
			}
			else 
			{
				STD_UI STD = new STD_UI(_CurrentSTD);
				STD.Show();
			}
		}
		#endregion

		#region Delete
		private void Delete_PackageTab_Click(object sender, EventArgs e)
		{
			if (_CurrentPackage == null)
			{
				MessageBox.Show("Please select one.");
			}
			else
			{
                if (MessageBox.Show("This Package will be permanently deleted, Are you sure about this?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    _DBAccessory.deletePackage(_CurrentPackage);
                    dgvPackageDataBind();
                }
			}
		}
		private void Delete_RawMaterialTab_Click(object sender, EventArgs e)
		{
			if (_CurrentRawMaterialSupplier == null)
			{
				MessageBox.Show("Please select one.");
			}
			else
			{
                if (MessageBox.Show("This Raw Material Supplier will be permanently deleted, Are you sure about this?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
				{
                    string code = _CurrentRawMaterialSupplier.Code;
                    try
                    {
                        _DBAccessory.deleteRawMaterialSupplier(_CurrentRawMaterialSupplier);
                        _DBAccessory.deleteIngredient(code);
                    }
                    catch (Exception _Ex)
                    {
                        MessageBox.Show("Delete data fail!" + "\nReason: " + _Ex.Message.ToString(), "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error,
                                MessageBoxDefaultButton.Button1
                                );
                    }
                    dgvRawMaterialSupplierDataBind();
                    dgvIngredientDataBind();
				}
			}
		}
		private void Delete_CurrencyTab_Click(object sender, EventArgs e)
		{
            DialogResult _curDeleResult = MessageBox.Show("This Currency will be permanently deleted, Are you sure about this?", "Warning",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Warning,
                MessageBoxDefaultButton.Button1);
            if (_curDeleResult == DialogResult.Yes)
            {
                try
                {
                    foreach (DataGridViewRow _row in dgvCurrency.SelectedRows)
                    {
                        dgvCurrency.Rows.Remove(_row);
                        this.cUR_EXCHTableAdapter.Update(this.gBDataSet.CUR_EXCH);
                        this.cUR_EXCHTableAdapter.Fill(this.gBDataSet.CUR_EXCH);
                    }
                }
                catch (Exception _Ex)
                {
                    throw new Exception(_Ex.Message);
                }
                //MessageBox.Show("Data has been successfully removed!", "Info",
                //        MessageBoxButtons.OK,
                //        MessageBoxIcon.Information,
                //        MessageBoxDefaultButton.Button1);
            }

            

            //if (_CurrentCurrency == null)
            //{
            //    MessageBox.Show("Please Select one");
            //}
            //else
            //{
            //    if (MessageBox.Show("This Currency will be deleted Permanently, Are you sure?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.OK)
            //    {
            //        string CurrencyName = _CurrentCurrency.CurrencyName;
            //        _DBAccessory.deleteCUR(CurrencyName);
            //        dgvCurrencyDataBind();
            //    }
            //    else
            //    {
					
            //    }
            //}
		}
		private void Delete_FreightTab_Click(object sender, EventArgs e)
		{
			if (_CurrentFreight == null)
			{
				MessageBox.Show("Please Select one");
			}
			else
			{
                if (MessageBox.Show("This Freight will be permanently deleted, Are you sure about this?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
				{
                    _DBAccessory.deleteFreight(_CurrentFreight);
                    dgvFreightDataBind();
				}
			}
		}
		private void Delete_IngredientTab_Click(object sender, EventArgs e)
		{
			if (_CurrentIngredient == null)
			{
				MessageBox.Show("Please Select one");
			}
			else
			{
                if (MessageBox.Show("This Ingredient will be permanently deleted, Are you sure about this?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
				{
                    _DBAccessory.deleteIngredientByIngredient(_CurrentIngredient);
                    dgvIngredientDataBind();
				}
			}
		}
		private void Delete_STDTab_Click(object sender, EventArgs e)
		{
			if (_CurrentSTD == null)
			{
				MessageBox.Show("Please Select one");
			}
			else
			{
                if (MessageBox.Show("This STD will be permanently deleted, Are you sure about this?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
				{
                    _DBAccessory.deleteSTD(_CurrentSTD);
                    dgvSTDDataBind();
				}
	
			}
		}
		private void Delete_SupplierTab_Click(object sender, EventArgs e)
		{
			if (_CurrentSupplier_RM == null)
			{
				MessageBox.Show("Please select one.");
			}
			else
			{
                if (MessageBox.Show("This Supplier RM will be permanently deleted, Are you sure about this?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
				{
                    _DBAccessory.deleteSupplierRM(_CurrentSupplier_RM);
                    dgvSupplierRMDataBind();
				}
			}
		}
		#endregion

		#region DataGridViewBinding
		private void setFromControlAndLoadData()
		{
			//this.dgvCurrency.DataSource = GetCurrencyList();
			this.dgvPackage.DataSource = GetPackageList();
			this.dgvRawMaterialSupplier.DataSource = GetRawSupplierList();
			this.dgvFreight.DataSource = GetFreightList();
			this.dgvIngredient.DataSource = GetIngredientList();
			this.dgvSupplierRM.DataSource = GetSupplierRMList();
			this.dgvSupplierRM.Visible = true;
			this.dgvSupplierRM.ReadOnly = true;
			this.dgvSTD.DataSource = GetSTDList();
			this.dgvSTD.Visible = true;
			this.dgvSTD.ReadOnly = true;
			this.dgvPackage.Visible = true;
			this.dgvPackage.ReadOnly = true;
			this.dgvFreight.Visible = true;
			this.dgvFreight.ReadOnly = true;
			this.dgvIngredient.Visible = true;
			this.dgvIngredient.ReadOnly = true;
			this.dgvRawMaterialSupplier.Visible = true;
			this.dgvRawMaterialSupplier.ReadOnly = true;
			//this.dgvCurrency.Visible = true;
			//this.dgvCurrency.ReadOnly = true;
		}
		private void dgvPackageDataBind() 
        {
            this.dgvPackage.DataSource = GetPackageList();
            this.dgvPackage.Visible = true;
            this.dgvPackage.ReadOnly = true;
        }
        //private void dgvCurrencyDataBind() 
        //{
        //    this.dgvCurrency.DataSource = GetCurrencyList();
        //    this.dgvCurrency.Visible = true;
        //    this.dgvCurrency.ReadOnly = true;
        //}
        private void dgvSTDDataBind() 
        {
            this.dgvSTD.DataSource = GetSTDList();
			this.dgvSTD.Visible = true;
			this.dgvSTD.Visible = true;
        }
        private void dgvSupplierRMDataBind() 
        {
            this.dgvSupplierRM.DataSource = GetSupplierRMList();
			this.dgvSupplierRM.Visible = true;
			this.dgvSupplierRM.ReadOnly = true;
        }
        private void dgvRawMaterialSupplierDataBind() 
        {
            this.dgvRawMaterialSupplier.DataSource = GetRawSupplierList();
            this.dgvRawMaterialSupplier.Visible = true;
            this.dgvRawMaterialSupplier.ReadOnly = true;
        }
        private void dgvFreightDataBind() 
        {
            this.dgvFreight.DataSource = GetFreightList();
            this.dgvFreight.Visible = true;
            this.dgvFreight.ReadOnly = true;
        }
        private void dgvIngredientDataBind() 
        {
            this.dgvIngredient.DataSource = GetIngredientList();
            this.dgvIngredient.Visible = true;
            this.dgvIngredient.ReadOnly = true;
        }
		#endregion

        private void ViewProductReport_QueryTab_Click(object sender, EventArgs e)
        {
            string _productID;
            _productID = this.ProductSelect_DropDownList_QueryTab.SelectedValue.ToString();
            GlobalParams.SetProductID(_productID);

            Reporting.Report_by_Product.ReportbyProduct _reportByProduct = new Reporting.Report_by_Product.ReportbyProduct();
            _reportByProduct.ShowDialog();
        }





		


		












        




    }
}
